package tailrec

import java.util.Random

object TestLoadBalance {

  def loadBalance(arr: Array[Int]): Int = {
    val list = arr.toList
    val weightSum: Int = list.sum
    val n = new Random().nextInt(weightSum)
    // n in [0, weightSum)
    var m = 0

    for (i <- 0 until  list.size) {
      if (m <= n && n < m + list(i)) {
        return i
      }
      m += list(i)
    }
    0
  }


  def loadBalance1(arr: Array[Int]): Int = {

    val segment: Array[Int] = arr.scan(0)(_+_).drop(0)

    val weightSum: Int = arr.sum

    val n = new Random().nextInt(weightSum)
    // n in [0, weightSum)
    for (i <- 0 until  segment.size) {
      if (n < segment(i)) {
        return i
      }
    }
    0
  }


  def main(args: Array[String]): Unit = {
    val arr = Array(3,1,6)
    val countMap  = collection.mutable.Map[Int,Int]()

    for(_ <- 1 to 100000) {
      val res = loadBalance1(arr)
      countMap.get(res) match {
        case Some(x) => countMap += (res -> (x+1))
        case None => countMap += (res -> 1)
      }
    }

    countMap.foreach(x => {
      println(s"${x._1} 调用次数 ${x._2}")
    })

  }


}
